<template>
  <v-snackbar v-model="snackbar" multi-line :style="{ bottom: `90%` }" timeout="1000" @click="snackbar = false"
    :color="color">
    <v-icon left>{{ text_ico }}</v-icon> {{ text }}
  </v-snackbar>
  <v-card>
    <v-card-actions>
      <v-col cols="1">
        <v-btn color="orange" @click="goBack">
          <v-icon start icon="mdi-arrow-left"></v-icon>
          Back
        </v-btn>
      </v-col>
      <v-col cols="9">
        <v-card-title style="text-align: center">
          <span class="headline">{{ articleTitle }}</span>
        </v-card-title>
      </v-col>
    </v-card-actions>
  </v-card>
  <v-container>
    <v-row>
      <v-col cols="1">
        <v-btn block rounded="xl" size="small" @click="SaveMd">保存</v-btn>
      </v-col>
      <v-col cols="1">
        <v-btn block rounded="xl" size="small" @click="exportMarkdown">md导出</v-btn>
      </v-col>
      <v-col cols="1">
        <v-btn block rounded="xl" size="small" @click="exportMarkdownZip">zip导出</v-btn>
      </v-col>
      <v-col cols="1">
        <v-btn block rounded="xl" size="small" @click="openm">历史记录</v-btn>
      </v-col>
      <div v-if="tab == '2'">
        <v-col cols="1">
          <v-btn size="small" @click="tabpre(1)" color="green">编辑</v-btn>
        </v-col>
      </div>
      <div v-if="tab == '1'">
        <v-col cols="1">
          <v-btn size="small" @click="tabpre(2)" color="yellow">预览</v-btn>
        </v-col>
      </div>
    </v-row>
  </v-container>

  <div v-if="tab == '1'">
    <MdEditor v-model="state.text" style="height: 100vh" :theme="state.theme" :codeTheme="state.codetheme"
      @onGetCatalog="onGetCatalog" :showToolbarName="true" @onUploadImg="onUploadImg" :autoDetectCode="true"
      :tableShape="[20, 20]" :autoFocus="true">
    </MdEditor>
  </div>

  <div v-if="tab == '2'">
    <v-container>
      <v-row no-gutters>
        <v-col cols="2">
          <v-navigation-drawer permanent>
            <v-sheet class="pa-2 ma-2">
              <MdCatalog :editorId="id" :scrollElement="scrollElement" />
            </v-sheet>
          </v-navigation-drawer>
        </v-col>
        <v-col>
          <v-sheet class="pa-2 ma-2">
            <MdPreview :editorId="id" :modelValue="state.text" />
          </v-sheet>
        </v-col>
      </v-row>
    </v-container>
  </div>

  <v-dialog v-model="modalOpen" persistent max-width="88%">
    <v-card>
      <v-row style="height: 15vh">
        <v-col cols="4">
          <v-sheet class="pa-2 ma-2">
            <v-card-title> 历史记录 </v-card-title>
          </v-sheet>
        </v-col>
        <v-col cols="4" offset="4">
          <v-sheet class="pa-2 ma-2">
            <v-card-actions class="justify-end">
              <v-btn icon="$close" variant="text" @click="closem"></v-btn>
            </v-card-actions>
          </v-sheet>
        </v-col>
      </v-row>
      <v-card-text>
        <v-table fixed-header height="40vh">
          <thead>
            <tr>
              <th class="text-left">id</th>
              <th class="text-left">标题</th>
              <th class="text-left">时间</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in items" :key="item.name">
              <td>{{ item._id }}</td>
              <td @click="saveold(index)">{{ item.task }}</td>
              <td>{{ item.date }}</td>
            </tr>
          </tbody>
        </v-table>
        <v-divider style="border-top-width: 10px; /* 自定义粗细 */"></v-divider>

        <v-row>
          <v-col cols="auto" class="me-auto">
            <v-sheet class="pa-2 ma-2">
              <v-btn @click="copyToCStr('old')"> 旧版copy </v-btn>
            </v-sheet>
          </v-col>
          <v-col cols="auto">
            <v-sheet class="pa-2 ma-2">
              <v-btn @click="copyToCStr('new')"> 新版copy </v-btn>
            </v-sheet>
          </v-col>
        </v-row>
        <code-diff :old-string="oldString" :new-string="newString" output-format="side-by-side" />
      </v-card-text>
      <v-card-actions>
        <v-btn text @click="closem">关闭模态框</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script>
import { MdEditor } from "md-editor-v3";
import { MdPreview, MdCatalog } from "md-editor-v3";
import "md-editor-v3/lib/style.css";
import "md-editor-v3/lib/preview.css";
import axios from "axios";
import { config } from "md-editor-v3";
import { lineNumbers } from "@codemirror/view";
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { useRoute } from "vue-router";
import { saveAs } from "file-saver";
import JSZip from "jszip";

export default {
  components: { MdEditor, MdPreview, MdCatalog },

  setup() {
    const snackbar = ref(false);
    const text = ref("");
    const color = ref("success");
    const text_ico = ref("mdi-check-circle");
    const modalOpen = ref(false); // 控制模态框的显示与隐藏
    const oldString = ref("");
    const newString = ref("");
    const route = useRoute();
    const items = ref([]);
    const tab = ref(1);
    const articleTitle = route.params.itemName;
    config({
      codeMirrorExtensions(_theme, extensions) {
        return [...extensions, lineNumbers()];
      },
    });
    const state = reactive({
      text: "",
      theme: "cyanosis",
      codetheme: "github",
      catalogList: []
    });
    const onGetCatalog = (list) => {
      state.catalogList = list;
    };
    const id = "preview-only";
    const scrollElement = document.documentElement;
    let content = ref("");

    // 图片上传事件
    const onUploadImg = async (files, callback) => {
      const res = await Promise.all(
        files.map((file) => {
          return new Promise((rev, rej) => {
            // 传给后端一个FormData数据，添加键值对，这里我添加了这个文章的ID和file
            const form = new FormData();
            form.append("file", file);
            axios
              // 这里是我的后端接口，请求地址和路径可以自己改
              .post("/api/md/img/upload", form, {
                headers: {
                  "Content-Type": "multipart/form-data",
                },
              })
              .then((res) => {
                console.log(res);
                rev(res);
              })
              .catch((error) => rej(error));
          });
        })
      );

      //   callback(res.map((item) => item.data.url));
      callback(res.map((item) => item.data.url));
    };
    function SaveMd() {
      const editorContent = state.text;
      axios
        // 这里是我的后端接口，请求地址和路径可以自己改
        .post("/api/md/save", { task: articleTitle, data: editorContent })
        .then((res) => {
          alertmsg(res.data.msg);
        })
        .catch((error) => {
          alertmsg(error);
        });
    }
    function alertmsg(t, ico, c) {
      if (ico === undefined) {
        ico = "mdi-check-circle";
      }
      if (c === undefined) {
        c = "success";
      }
      color.value = c;
      text.value = t;
      text_ico.value = ico;
      snackbar.value = true;
    }
    function getMdPro() {
      axios
        .post("/api/md/pro/get", { task: articleTitle })
        // 发送GET请求到后端API
        .then((response) => {
          state.text = response.data.data;
          console.log(response);
        })
        .catch((error) => {
          // 处理请求错误
          alertmsg("获取md文档失败", "mdi-cancel", "error");
          console.error(error);
        });
    }
    function openm() {
      axios
        .post("/api/md/pro/get/all", { task: articleTitle })
        // 发送GET请求到后端API
        .then((response) => {
          items.value = response.data;
          console.log(items.value);
          newString.value = state.text;
          modalOpen.value = true;
        })
        .catch((error) => {
          // 处理请求错误
          alertmsg("获取md文档失败", "mdi-cancel", "error");
          console.error(error);
        });
    }
    function closem() {
      modalOpen.value = false;
    }
    function saveold(e) {
      const result = items.value[e];
      oldString.value = result.data;
      alertmsg("比对完成");
    }
    function goBack() {
      history.back(); // 返回到上一次页面
    }
    function exportMarkdown() {
      const markdownText = state.text;
      const fileBlob = new Blob([markdownText], { type: "text/markdown" });
      saveAs(fileBlob, articleTitle + ".md");
      const msg = "导出" + articleTitle + "成功";
      alertmsg(msg);
    }
    function exportMarkdownZip() {
      const markdownText = state.text;
      const regex = /!\[\]\((.*?)\)/g;
      const matches = [];
      let Text = markdownText;
      let imgArray = [];
      let match;
      while ((match = regex.exec(markdownText))) {
        const content = match[1];
        matches.push(content);
      }
      if (matches.length > 0) {
        matches.forEach(function (item) {
          const imgName = item.split("/").pop();
          imgArray.push(imgName);
          Text = Text.replace(item, "./img/" + imgName);
        });
      }

      const zip = new JSZip();
      zip.file(articleTitle + ".md", Text);
      axios.post("/api/md/img/get", { task: matches }).then((res) => {
        const item = res.data.data;
        if (item) {
          item.forEach(function (item) {
            const byteCharacters = atob(item.data);
            const byteArrays = [];
            for (let i = 0; i < byteCharacters.length; i++) {
              byteArrays.push(byteCharacters.charCodeAt(i));
            }
            const blob = new Blob([new Uint8Array(byteArrays)], {
              type: "image/png",
            });
            zip.file("./img/" + item.name, blob);
          });
        }

        zip.generateAsync({ type: "blob" }).then((content) => {
          saveAs(content, articleTitle + ".zip");
        });
        alertmsg(res.data.msg);
      });

      // 生成压缩包
    }
    onMounted(() => {
      getMdPro();
      document.title = `文档 - ` + articleTitle;
      window.addEventListener("keydown", handleKeyDown);
    });
    onBeforeUnmount(() => {
      window.removeEventListener("keydown", handleKeyDown);
    });
    // 处理键盘事件的函数
    function handleKeyDown(event) {
      if (event.ctrlKey && event.key === "s") {
        SaveMd();
        alertmsg("保存成功");
      }
    }
    function copyToCStr(e) {
      let textToCopy;
      if (e === "new") {
        textToCopy = state.text;
        console.log(textToCopy, 1);
      } else {
        textToCopy = oldString.value;
        console.log(textToCopy, 2);
      }
      let inputDom = document.createElement("textarea"); // js创建一个文本框
      document.body.appendChild(inputDom); //将文本框暂时创建到实例里面
      inputDom.value = textToCopy; //将需要复制的内容赋值到创建的文本框中
      inputDom.select(); //选中文本框中的内容
      inputDom.focus();
      document.execCommand("copy"); //执行复制操作
      document.body.removeChild(inputDom); //最后移出
      // navigator.clipboard
      //   .writeText(textToCopy)
      //   .then(() => {
      alertmsg("已复制到剪贴板");
      //   })
      //   .catch(() => {
      //     alertmsg("复制失败");
      //   });
    }
    function tabpre(e) {
      tab.value = e;
    }
    return {
      snackbar,
      text,
      color,
      text_ico,
      articleTitle,
      content,
      state,
      modalOpen,
      oldString,
      newString,
      items,
      tab,
      id,
      scrollElement,
      onGetCatalog,
      SaveMd,
      onUploadImg,
      openm,
      closem,
      saveold,
      goBack,
      exportMarkdown,
      exportMarkdownZip,
      copyToCStr,
      tabpre,
    };
  },
};
</script>
